package csc.fresher.finalgroupfour.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import botdetect.web.Captcha;
import csc.fresher.finalgroupfour.domain.User;
import csc.fresher.finalgroupfour.service.UserService;

public class BotDetect implements AuthenticationSuccessHandler {

	@Autowired
	private UserService userService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest req,
			HttpServletResponse res, Authentication authentication)
			throws IOException, ServletException {
		req.getParameter("captchaCodeTextBox");
		HttpSession session = req.getSession();

		// Get current user's loginId
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String loginId = auth.getName(); // get logged in Id
		User user = userService.findUser(loginId);

		// Get the captcha and do validation
		Captcha captcha = Captcha.load(req, "springFormCaptcha");
		boolean isHuman = captcha.validate(req,
				req.getParameter("captchaCodeTextBox"));
		if (isHuman) {
			// TODO: Captcha validation passed, perform protected action
			user.setAttemptedLogin(0); // Reset # of attempted login
			session.setAttribute("errorMessage", null);
			userService.updateUser(user);
			res.sendRedirect("home");
		} else {
			// TODO: Captcha validation failed, show error message
			user.setAttemptedLogin(user.getAttemptedLogin() + 1);
			userService.updateUser(user);
			SecurityContextHolder.clearContext();
			session.setAttribute("errorMessage", "Invalid Captcha");

			if (user.getAttemptedLogin() >= 3
					|| !user.getUserState().equalsIgnoreCase("enabled")) {
				user.setUserState("disabled");
				session.setAttribute("errorMessage",
						"Your account has been locked");
				user.setAttemptedLogin(0);
				userService.updateUser(user);
			}
			res.sendRedirect("login?error=true");
		}
	}
}
